package me.shurufa.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;

import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.Utils;


/**
 * Created by kHRYSTAL on 15/7/23.
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            EventBus.getDefault().register(this);
            Global.mWxApi.handleIntent(getIntent(), this);
        } catch (Exception e) {
            Utils.showToast(R.string.umeng_socialize_text_tencent_oauth_login_fail);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {
            Global.mWxApi.handleIntent(intent, this);
        } catch (Exception e) {
            Utils.showToast(R.string.umeng_socialize_text_tencent_oauth_login_fail);
        }
    }


    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        if (baseResp instanceof SendAuth.Resp) {
            // LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
            // Intent intent = new Intent(Constants.ACTION_WECHAT_LOGIN);
            // intent.putExtra("result", baseResp.errCode == BaseResp.ErrCode.ERR_OK);
            // intent.putExtra("code", ((SendAuth.Resp) baseResp).code);
            // lbm.sendBroadcast(intent);
            // finish();

            Intent in = new Intent(Constants.ACTION_AUTH_WEIXIN);
            in.putExtra("code", ((SendAuth.Resp) baseResp).code);
            EventBus.getDefault().post(in);
            finish();

        } else {
            int result = 0;
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    result = R.string.errcode_success;
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    result = R.string.errcode_cancel;
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    result = R.string.errcode_deny;
                    break;
                default:
                    result = R.string.errcode_unknown;
                    break;
            }

            Toast.makeText(this, getString(result), Toast.LENGTH_LONG).show();
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(Intent intent) {
    }
}
